package com.example.wisdombookstore.task;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.example.wisdombookstore.entity.RlCheckBookType;
import com.example.wisdombookstore.entity.TbBookType;
import com.example.wisdombookstore.entity.TbClerk;
import com.example.wisdombookstore.entity.TbCron;
import com.example.wisdombookstore.mapper.*;
import com.example.wisdombookstore.service.ICheckTaskService;
import com.example.wisdombookstore.util.DateTime;
import com.example.wisdombookstore.util.IdWorker;
import com.example.wisdombookstore.util.ResponseResult;
import com.example.wisdombookstore.util.StateConstant;
import lombok.extern.slf4j.Slf4j;
import org.springframework.scheduling.annotation.EnableAsync;
import org.springframework.scheduling.annotation.EnableScheduling;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.scheduling.annotation.SchedulingConfigurer;
import org.springframework.scheduling.config.ScheduledTaskRegistrar;
import org.springframework.scheduling.support.CronTrigger;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;

import javax.annotation.Resource;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.List;

/**
 * @program: wisdombookstore
 * @description: 盘点定时任务
 * @author: 陈阳
 * @create: 2020-10-28 11:49
 */
@EnableScheduling
@Component
@Slf4j
@EnableAsync
public class TbCheckTask  implements SchedulingConfigurer {

    @Resource
    private ICheckTaskService iCheckTaskService;

    @Resource
    private IdWorker idWorker;

    @Resource
    private TbClerkMapper tbClerkMapper;

    @Resource
    private TbBookTypeMapper tbBookTypeMapper;

    @Resource
    private TbCronMapper tbCronMapper;

    @Resource
    private TbCheckTaskMapper tbCheckTaskMapper;

    /*
    * TODO 陈阳   盘点定时任务
    *   获取所有员工
    *   获取所有盘点类型
    *   调用添加盘点任务方法
     * @Description:
     * @Author: 陈阳
     * @Date: 2020/10/28 13:39
     * @param null:
     * @return: null
     **/

    @Scheduled(cron = "00 03 15 * * *")
    public void task(){
        //查询盘点任务
        //进行日期判断
        log.info("查询最后一次定时任务");
        LambdaQueryWrapper<com.example.wisdombookstore.entity.TbCheckTask> tbCheckTaskLambdaQueryWrapper = new QueryWrapper<com.example.wisdombookstore.entity.TbCheckTask>()
                .lambda()
                .orderByDesc(com.example.wisdombookstore.entity.TbCheckTask::getCreateTime).last("limit 1");
        com.example.wisdombookstore.entity.TbCheckTask tbCheckTasks = this.tbCheckTaskMapper.selectOne(tbCheckTaskLambdaQueryWrapper);
        //系统时间
        Date date = DateTime.getDate();
        System.err.println(tbCheckTasks);
        Date createTime = null;
        if(tbCheckTasks!=null){
            createTime = tbCheckTasks.getCreateTime();
            //System.err.println("继续执行任务1");
        }
        if(createTime==null){
            log.info("添加任务");
        }
        if(tbCheckTasks!=null){
            //System.err.println("继续执行任务2");
            boolean before = date.before(createTime);
            if(before){
                log.info("请联系执行人尽快完成现有的任务");
                return ;
            }
        }
        //查询所有的店员
        log.info("查询所有的店员");
        LambdaQueryWrapper<TbClerk> last = new QueryWrapper<TbClerk>()
                .lambda()       //StateConstant.TBCLERK_STATUS_WORK
                .eq(TbClerk::getStatus, StateConstant.OBJECT_DEL_NORMAL);
        List<TbClerk> tbClerks = this.tbClerkMapper.selectList(last);
        if (tbClerks.size() == 0) {
            //退出程序
            //System.exit(0);
            return ;
        }
        System.err.println("店员数量"+tbClerks.size());

        com.example.wisdombookstore.entity.TbCheckTask tbCheckTask = new com.example.wisdombookstore.entity.TbCheckTask();
        //添加盘点任务
        tbCheckTask.setId(null);
        tbCheckTask.setCode(idWorker.nextId());
        tbCheckTask.setIsDel(StateConstant.OBJECT_DEL_NORMAL);
        tbCheckTask.setCreateTime(new Date());
        tbCheckTask.setUpdateTime(null);
        tbCheckTask.setStatus(StateConstant.TBCHECKTASK_STATUS_STAY);
        //任务开始时间
        tbCheckTask.setStartCheckDate(new Date());
        //随机去除员工集合中的一个
        int v = (int) Math.random() * tbClerks.size();
        tbCheckTask.setTbClerkCode(tbClerks.get(v).getCode());
        //获取系统时间
        SimpleDateFormat sf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        Calendar c = Calendar.getInstance();
        log.info("当前日期:"+sf.format(c.getTime()));
        //时间增加一天
        c.add(Calendar.HOUR_OF_DAY, 1);
        log.info("增加一小时后的日期:"+sf.format(c.getTime()));
        //任务结束时间
        tbCheckTask.setEndCheckDate(c.getTime());
        LambdaQueryWrapper<TbBookType> eq = new QueryWrapper<TbBookType>()
                .lambda()
                .eq(TbBookType::getIsDel, StateConstant.OBJECT_DEL_NORMAL);
        List<TbBookType> tbBookTypes = this.tbBookTypeMapper.selectList(eq);
        String a  = "";
        //循环拼接盘点类型
        for(TbBookType type:tbBookTypes){
            a += ","+type.getCode();
        }
        a = a.substring(1);
        tbCheckTask.setTypeJoint(a);
        System.err.println(tbCheckTask);
        log.info(tbCheckTask.toString());
        System.err.println("===============");
        log.info("执行添加盘点任务方法");
        ResponseResult responseResult = this.iCheckTaskService.addCheck(tbCheckTask);
        log.info(responseResult.toString());

    }

    /*
    * TODO 陈阳  读取数据库中存放的最新的一条执行规则
     * @Description:
     * @Author: 陈阳
     * @Date: 2020/10/28 21:54

     * @return: java.lang.String   执行的规则
     **/
    public String cronMapper(){
        LambdaQueryWrapper<TbCron> tbCronLambdaQueryWrapper = new QueryWrapper<TbCron>()
                .lambda()
                .eq(TbCron::getIsDel, StateConstant.OBJECT_DEL_NORMAL)
                .last("limit 1")
                .orderByDesc(TbCron::getCreateTime);
        TbCron tbCron = this.tbCronMapper.selectOne(tbCronLambdaQueryWrapper);
        long l = idWorker.nextId();
        if(tbCron==null){
            tbCron = new TbCron();
            tbCron.setId(null);
            System.err.println("执行初始化方法");
            tbCron.setCron(String.valueOf(l));
            tbCron.setIsDel(StateConstant.OBJECT_DEL_NORMAL);
            tbCron.setCreateTime(new Date());
            tbCron.setUpdateTime(null);
            tbCron.setCron("* 00 16 * * *");
            int insert = tbCronMapper.insert(tbCron);
            LambdaQueryWrapper<TbCron> tbCronLambdaQueryWrapper1 = new QueryWrapper<TbCron>()
                    .lambda()
                    .eq(TbCron::getIsDel, StateConstant.OBJECT_DEL_NORMAL)
                    .last("limit 1")
                    .orderByDesc(TbCron::getCreateTime);
            tbCron = this.tbCronMapper.selectOne(tbCronLambdaQueryWrapper1);
        }
        return tbCron.getCron();
    }

    @Override
    public void configureTasks(ScheduledTaskRegistrar scheduledTaskRegistrar) {
        scheduledTaskRegistrar.addTriggerTask(
                //1.添加任务内容(Runnable)
                //() -> System.out.println("执行定时任务2: " + LocalDateTime.now().toLocalTime()),
                () -> this.task(),
                //2.设置执行周期(Trigger)
                triggerContext -> {
                    //2.1 从数据库获取执行周期
                    //String cron = scheduledTaskRegistrar.getCron();
                    //2.2 合法性校验.
                    if (this.cronMapper()==null) {
                        // Omitted Code ..
                    }
                    //2.3 返回执行周期(Date)
                    return new CronTrigger(this.cronMapper()).nextExecutionTime(triggerContext);
                }
        );
    }
}
